package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;

import edu.ynu.se.xiecheng.achitectureclass.dao.*;
import edu.ynu.se.xiecheng.achitectureclass.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


@Service
public class CustomerService extends LogicService<CustomerDao, Customer,Long> {
    @Resource
    private ShopDao shopDao;

    @Resource
    private ItemDao itemDao;
    @Resource
    private LineItemDao lineItemDao;
    @Resource
    private OorderDao oorderDao;
    public CustomerService(@Autowired CustomerDao cd) {
        super(cd);
    }
    public Oorder addOorder(Long customerId,Long shopId){
        Customer customer = getDAO().getReferenceById(customerId);
        Shop shop = shopDao.getReferenceById(shopId);
        return oorderDao.save(customer.addOorder(shop));
    }
    public LineItem selectShopItem(Long customerId, Long shopId, Long orderId, Long itemId, Integer quantity){
        Customer customer = getDAO().getReferenceById(customerId);
        Shop shop = shopDao.getReferenceById(shopId);
        Oorder oorder = oorderDao.getReferenceById(orderId);
        Item item = itemDao.getReferenceById(itemId);
        return lineItemDao.save(customer.selectShopItem(shop, oorder, item,quantity));
    }
    public Oorder pay(Long customerId,Long orderId){
        Customer customer = getDAO().getReferenceById(customerId);
        return oorderDao.save(customer.pay(oorderDao.getReferenceById(orderId)));
    }

    public void deleteOrder(Long oorderId){
        Oorder oorder = oorderDao.getReferenceById(oorderId);
        if(oorder.getPayStatus()==0){
            oorderDao.delete(oorder);
            lineItemDao.deleteAll(oorder.getLineItems());
        }
    }

    public Customer register(String username, String password){
        Customer customer = getDAO().findByUsername(username);
        if(customer == null){
            customer = new Customer();
            return getDAO().save(customer.register(username, password));
        }
        return customer;
    }
    public Customer login(String username, String password){
        return getDAO().findByUsernameAndPassword(username, password);
    }


}
